#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MaterialList.h"

MaterialList::MaterialList()
{
	head = NULL;
	tail = NULL;
}
MaterialList::MaterialList(Material * headMaterial)
{
	head = new List<Material>(headMaterial, NULL);
	tail = head;
}
MaterialList::~MaterialList()
{
	printf("deleting vector list\n");
	List<Material> * search = head;
	int i = 0;
	while(search)
	{
		printf("vector number %d\n",i);
		i++;
		search = search->RemoveList();
	}
	head = NULL;
	printf("done deleting vectors\n");
}
List<Material> * MaterialList::Add(Material * payload)
{
	head = new List<Material>(payload, head);
	if(tail == NULL)
		tail = head;
	return head;
}

void MaterialList::Remove(Material * point)
{
	List<Material> * search = head;
	while(search)
	{
		if(search->payload && search->payload ==  point)
		{
			if(search == head)
			{
				head = search->next;
			}
			else if(search == tail)
			{
				tail = search->prev;
			}
			search = search->Remove();
			break;
		}
		else
			search = search->next;
	}	
}

char * MaterialList::GetTag()
{
	List<Material> * search = tail;
	
	int length = 0;
	char * tag = NULL;
	
	while(search)
	{
		if(search->payload)
		{
			char * point = search->payload->GetTag();
			int endLine = 0;
			if(search->prev)
				endLine = 1;
			tag = (char *)realloc(tag, (length + strlen(point) + 1 + endLine) * sizeof(char));
			memcpy(tag+length,point, strlen(point)+1);
	
			if(endLine)
			{
				int len = strlen(tag);
				tag[len] = '\n';
				tag[len+1]='\0';
			}
			length += strlen(point)+endLine;
			delete point;
		}
		search = search->prev;
	}
	return tag;
}
int MaterialList::GetLength()
{
	List<Material> * search = head;
	int i =0;
	while(search)
	{
		i++;
		search = search->next;
	}
	return i;
}
char ** MaterialList::GetNames()
{
	char ** names = (char**)malloc(sizeof(char*)*GetLength());
	List<Material> * search = head;
	int i =0;
	while(search)
	{
		if(search->payload)
		{
			names[i] = search->payload->name;
		}
		search = search->next;
	}
	return names;
}
Material * MaterialList::GetMaterial(char * name)
{
	List<Material> * search = head;
	while(search)
	{
		if(search->payload)
		{
			if(strcmp(name, search->payload->name) == 0)
				return search->payload;
		}
		search = search->next;
	}
	return NULL;
}
